<template>
  <div class="app-pipeline-container">
    <!-- 搜索列 -->
    <div class="table-search-columns" v-show="showSearch">
      <a-form-model class="app-pipeline-search-form" ref="query" :model="query">
        <a-row>
          <a-col :span="5">
            <a-form-model-item label="名称" prop="name">
              <a-input v-model="query.name" allowClear/>
            </a-form-model-item>
          </a-col>
          <a-col :span="5">
            <a-form-model-item label="描述" prop="description">
              <a-input v-model="query.description" allowClear/>
            </a-form-model-item>
          </a-col>
          <a-col :span="5">
            <a-form-item>
              <a-button type="primary" @click.native.prevent="getList()">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetForm">重置</a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <!-- 工具栏 -->
    <div class="table-tools-bar">
      <!-- 左侧 -->
      <div class="tools-fixed-left">
        <span class="table-title">流水线列表</span>
        <a-divider v-show="selectedRowKeys.length" type="vertical"/>
        <a-popconfirm v-show="selectedRowKeys.length"
                      placement="topRight"
                      title="是否删除选中流水线?"
                      ok-text="确定"
                      cancel-text="取消"
                      @confirm="batchDelete(selectedRowKeys)">
          <a-button class="ml8" type="danger" icon="delete">删除</a-button>
        </a-popconfirm>
      </div>
      <!-- 右侧 -->
      <div class="tools-fixed-right">
        <a-button v-if="query.profileId" class="ml16 mr8" type="primary" icon="plus" @click="add">新建</a-button>
        <a-divider v-if="query.profileId" type="vertical"/>
<!--        <a-icon type="search" class="tools-icon" title="查询" @click="getList()"/>-->
<!--        <a-icon type="reload" class="tools-icon" title="重置" @click="resetForm"/>-->
        <search-toolbar :showSearch.sync="showSearch" @refresh="getList()"></search-toolbar>
      </div>
    </div>
    <!-- 表格 -->
    <div class="table-main-container table-scroll-x-auto">
      <a-table :columns="columns"
               :dataSource="rows"
               :pagination="pagination"
               :rowSelection="{selectedRowKeys, onChange: e => selectedRowKeys = e}"
               rowKey="id"
               @change="getList"
               :scroll="{x: '100%'}"
               :loading="loading"
               size="middle">
        <!-- 修改时间 -->
<!--        <template v-slot:updateTime="record">-->
<!--          {{ record.updateTime | formatDate }}-->
<!--        </template>-->
        <!--触发方式-->
        <span slot="triggerWay" slot-scope="trigger">
          <a-tag v-if="trigger === 'hand'" color="cyan">手动触发</a-tag>
          <a-tag v-else-if="trigger === 'code'" color="green">提交代码</a-tag>
          <a-tag v-else-if="trigger === 'webhook'" color="blue">webhook</a-tag>
          <a-tag v-else-if="trigger === 'timing'" color="orange">定时触发</a-tag>
        </span>
        <!-- 操作 -->
        <template v-slot:action="record">
<!--          &lt;!&ndash; 执行 &ndash;&gt;-->
<!--          <span class="span-blue pointer" @click="execPipeline(record.id)">执行</span>-->
<!--          <a-divider type="vertical"/>-->
<!--          &lt;!&ndash; 详情 &ndash;&gt;-->
<!--          <span class="span-blue pointer" @click="openDetail(record.id)">详情</span>-->
<!--          <a-divider type="vertical"/>-->
          <!--记录-->
          <span class="span-blue pointer" @click="handleRecord(record)">记录</span>
          <a-divider type="vertical"/>
          <!-- 配置 -->
<!--          <span class="span-blue pointer" @click="update(record.id)">配置</span>-->
          <span class="span-blue pointer" @click="update(record)">配置</span>
          <a-divider type="vertical"/>
          <!-- 删除 -->
          <a-popconfirm title="确认删除当前流水线?"
                        placement="topRight"
                        ok-text="确定"
                        cancel-text="取消"
                        @confirm="remove(record.id)">
            <span class="span-blue pointer">删除</span>
          </a-popconfirm>
        </template>
      </a-table>
    </div>
    <!-- 事件 -->
    <div class="app-pipeline-event">
      <!-- 流水线操作抽屉 -->
      <AppPipelineDetailViewDrawer ref="detailViewDrawer"/>
      <!-- 添加/修改模态框 -->
<!--      <AddPipelineModal ref="addModal" @added="getList()" @updated="getList"/>-->
      <flowcanvas  v-if="addVisible" ref="flowcanvas" @refreshDataList="getList"></flowcanvas>
      <record v-if="recordVisible" ref="record" @refreshDataList="getList"></record>
      <!-- 流水线执行模态框 -->
      <AppPipelineExecModal ref="execModal" :visibleReselect="false"/>
    </div>
  </div>
</template>

<script>

import AppPipelineDetailViewDrawer from '@/components/app/AppPipelineDetailViewDrawer'
import _filters from '@/lib/filters'
import AddPipelineModal from '@/components/app/AddPipelineModal'
import flowcanvas from "../pipeline/flowcanvas";
import record from "@/views/pipeline/record/record.vue";
import AppPipelineExecModal from '@/components/app/AppPipelineExecModal'
import toolbar from '@/mixins/search-toolbar-mixin'
// import record from "../pipeline/record/record";

/**
 * 列
 */
const columns = [
  {
    title: '名称',
    key: 'pipelineName',
    dataIndex: 'pipelineName',
    ellipsis: true,
    width: 200,
    sorter: (a, b) => a.name.localeCompare(b.name)
  },
  {
    title: '创建人',
    dataIndex: 'creator',
    key: 'creator',
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    width: 200,
    ellipsis: true
  },
  // {
  //   title: '修改时间',
  //   key: 'updateTime',
  //   width: 150,
  //   sorter: (a, b) => a.updateTime - b.updateTime,
  //   scopedSlots: { customRender: 'updateTime' }
  // },
  {
    title: '触发方式',
    dataIndex: 'triggerWay',
    key: 'triggerWay',
    scopedSlots: { customRender: 'triggerWay' }
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 250,
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'AppPipeline',
  components: {
    AppPipelineExecModal,
    // AddPipelineModal,
    flowcanvas,
    AppPipelineDetailViewDrawer,
    record
  },
  mixins: [toolbar],
  data: function() {
    return {
      //画布可见
      addVisible: false,
      recordVisible:false,

      query: {
        profileId: undefined,
        name: '',
        description: ''
      },
      rows: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showTotal: function(total) {
          return `共 ${total} 条`
        }
      },
      selectedRowKeys: [],
      loading: false,
      columns
    }
  },
  methods: {
    chooseProfile({ id }) {
      this.query.profileId = id
      this.getList()
    },
    getList(page = this.pagination) {
      this.loading = true
      this.$api.getAppPipelineList({
        ...this.query,
        queryDetail: 1,
        pageIndex: page.current,
        pageSize: page.pageSize
      }).then((res) => {
        const pagination = { ...this.pagination }
        pagination.total = res.totalCount
        pagination.current = res.pageIndex
        this.rows = res.data || []
        this.pagination = pagination
        this.selectedRowKeys = []
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    batchDelete(ids) {
        this.$api.batchDeleteAppPipeline(
          ids
        ).then(() => {
          this.selectedRowKeys = []
          this.$antdmessage.success('删除成功')
          this.getList()
        })
    },

    remove(id) {
      this.$api.deleteAppPipeline({
        id
      }).then(() => {
        this.selectedRowKeys = []
        this.$antdmessage.success('删除成功')
        this.getList()
      })
    },

    //这里嫁接流水线画布编排
    // add() {
    //   this.$refs.addModal.add()
    // },
    add() {
      // if (!this.queryParams.applicationUuid){
      //   this.msgError('请选择应用')
      //   return
      // }
      // this.form.applicationUuid = this.queryParams.applicationUuid
      // let appUuid = this.queryParams.applicationUuid
      this.addVisible = true
      this.$nextTick(() => {
        this.$refs.flowcanvas.init('', 0,null,false) //停用前两个字段，本版本暂不需要绑定应用的概念
      })
    },
    // update(id) {
    //   this.$refs.addModal.update(id)
    // },
    update(record) {
      this.addVisible = true
      this.$nextTick(() => {
        this.$refs.flowcanvas.init(record.name,record.id,record.id,false)
      })
    },
    handleRecord(row){
      this.recordVisible = true
      this.$nextTick(() => {
        this.$refs.record.init(row.uuid)
      })
    },


    execPipeline(id) {
      this.$refs.execModal.openPipeline(this.query.profileId, id)
    },
    openDetail(id) {
      this.$refs.detailViewDrawer.open(id)
    },
    resetForm() {
      this.$refs.query.resetFields()
      // this.getList()
    }
  },
  async mounted() {
    // 读取当前环境
    const activeProfile = this.$storage.get(this.$storage.keys.ACTIVE_PROFILE)
    if (!activeProfile) {
      this.$antdmessage.warning('请先维护应用环境')
      return
    }
    this.query.profileId = JSON.parse(activeProfile).id
    this.getList()
  },
  filters: {
    ..._filters
  }
}
</script>

<style scoped>
.pipeline-stage-wrapper {
  display: contents;
}
</style>
